﻿using CWCS.Common;
using CWCS.Common.Log;
using CWCS.Core.Library.PLCManager;
using CWCS.DataAccess;
using CWCS.DataAccess.DataProvider;
using CWCS.Entity;
using CWCS.Entity.Convery;
using CWCS.Entity.SRM;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using CWCS.Entity.Robot;
//using CWCS.Core.Library.ModbusManager;
using CWCS.BLL.WebsocketCommon;
using SuperWebSocket;
using System.Collections.Concurrent;
using static CWCS.BLL.PhotoBLL;

namespace CWCS.BLL
{
    public class ConveryBLL : BLLBase
    {
        private LogHelper stalog;
        private LogHelper staTimelog;
        LED_UDP led = new LED_UDP();
        ScanBLL scanBLL = new ScanBLL();
        SmartBLL smartBLL = new SmartBLL();
        // private static LED_UDP led;
        public int LEDFlag = 1;
        public string LedString = "设备运行中，请注意安全！";
        public string LedStringOld = "";
        public static Thread LEDThread;
        bool ledflag = true;
        private static Dictionary<string, string> LEDSendStr = new Dictionary<string, string>();
        private static Dictionary<string, string> stationlog = new Dictionary<string, string>();
        private static Dictionary<string, int> stationDSalarm = new Dictionary<string, int>();//用于记录顶升站台的报警信息,大于设定周期进行报警
        private string ledmsg;
        private string[] HCLEDStation = new string[] { "1221", "1277" };
        private string[] FRLEDStation = new string[] { "2257", "2201" };
        private string[] LEDStation = new string[] { };//LED编号


        private List<string> oldTostation1670 = new List<string> { "1679", "1682" };
        private List<string> oldTostation1624 = new List<string> { "1627", "1630" };
        private List<string> oldTostation1673 = new List<string> { "1682" };
        private List<string> oldTostation1007 = new List<string> { "1008", "1011" };
        private List<string> oldTostation1710 = new List<string> { "1901" };
        private List<string> tostationCD = new List<string> { "1902", "1902" };
        private List<string> oldTostation1507 = new List<string> { "1512", "1510" };

        private List<string> oldTostation2102 = new List<string> { "2213","2117", "2120" };
        private List<string> oldTostation2202 = new List<string> { "2218" };
        private List<string> oldTostation2072 = new List<string> { "2075", "2081" };
        private List<string> oldTostation2308 = new List<string> { "2901","2314","2902","2318"};
        private List<string> oldTostation1408 = new List<string> { "1411", "1414" };
        private List<string> oldTostation2604 = new List<string> { "2605", "2608" };
        private List<string> oldTostation2041 = new List<string> { "2045", "2044" };
        private List<string> oldTostation2048 = new List<string> { "2049" };
        private List<string> oldTostation2052 = new List<string> { "2053" };
        private List<string> oldTostation2218 = new List<string> { "2228" };
        private List<string> oldTostation1905 = new List<string> { "1906" };
        private List<string> oldTostation2044 = new List<string> { "2045" };

        private List<string> oldTostation1029 = new List<string> { "1033", "1031" };
        private List<string> oldTostation1116 = new List<string> { "1120", "1118" };
        private List<string> oldTostation1509 = new List<string> { "1513", "1511" };
        private List<string> oldTostation1462 = new List<string> { "1466", "1464" };
        private List<string> oldTostation1305 = new List<string> { "1309", "1307" };
        private List<string> oldTostation1722 = new List<string> { "1726", "1724" };
        private List<string> oldTostationTEST = new List<string> { "1234", "1724" };

        private ConcurrentDictionary<string, ArriveInfo> arriveTime = new ConcurrentDictionary<string, ArriveInfo>();  //1606与1709站台到位时间集合
        private ConcurrentDictionary<string, ArriveInfo> arriveTimeCD = new ConcurrentDictionary<string, ArriveInfo>();  //1902,1903站台到位时间集合


        #region Event

        public delegate void ShowLogMessage(string type, string msg);
        public event ShowLogMessage ShowLogMsg;

        public delegate void ShowConverysPLCStatus(string strip, string strDuration, bool b_ConnectStatus);
        public event ShowConverysPLCStatus ShowStationPLCStatus;

        public delegate void NotifiedUI(List<ConveryEntity> lst);
        public event NotifiedUI ShowStationStatus;

        public delegate void Notified(List<RobotInfo> robotBLLs);
        public event Notified ShowRobotStatus;

        #endregion

        public ConveryBLL()
        {
            try
            {
                stalog = new LogHelper("Convery");
                staTimelog = new LogHelper("ConveryTime");

                //plc = new ConveryModbus();
                plc = new ConveryPLC();
                plc.ShowPLCStatus += new PLCHelper.ShowPLCConnectStatus(ShowConveryPLCStatus);//连接状态
                plc.ShowStatus += new PLCHelper.ShowEquipmentStatus(NotifityUIConveryStatus);//界面显示
                plc.GetTaskInfo += new PLCHelper.GetPLCTaskInfo(DoWork);//业务逻辑处理

                scanBLL.AddScanConfigure();
                startLED();
            }
            catch (Exception ex)
            {
                stalog.Debug("ConveryBLL初始化时异常", ex);
                stalog.Info(string.Format("{0}初始化时异常"), new object[] { "" });
            }
        }

        public void startLED()
        {
            try
            {
                LEDStation = ZoneCode == "HC" ? HCLEDStation : FRLEDStation;
                for (int i = 0; i < LEDStation.Length; i++)
                {
                    led.DLed.Add(LEDStation[i], new LED_UDP(LEDStation[i], System.Configuration.ConfigurationSettings.AppSettings[ZoneCode + "LED" + LEDStation[i].ToString()].ToString(), "5005", "BX_5MK1"));
                    led.init(LEDStation[i]);
                    led.send_Msg(LEDStation[i], "alarm", "成就客户，诚信务实！");
                }
            }
            catch (Exception ex)
            {
                stalog.Debug("ConveryBLL初始化时异常", ex);
                stalog.Info(string.Format("{0}初始化时异常"), new object[] { "" });
            }
        }

        #region 输送机配置

        public bool InsertOPCData(List<WCS_OPCITEM> lst, ref string msg)
        {
            msg = "";
            try
            {
                int i = DataAccessFactory.Instance.BatchInsert<WCS_OPCITEM>(lst);
                return i > 0;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
        }

        public DataTable GetWCS_OPCItem()
        {
            try
            {
                DataTable dt = new DataTable();
                DataSet ds = DataAccessFactory.Instance.ExecuteDataSet("select * from WCS_OPCItem where areacode='" + AreaCode + "-" + LineCode + "-" + ZoneCode + "' and status <> '0'  and groupname='Convery'  order BY userid,stationno", CommandType.Text, null);
                if (ds != null && ds.Tables.Count > 0)
                    dt = ds.Tables[0];
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool UpdateOPCItem(WCS_OPCITEM entity)
        {
            try
            {
                //stalog.Info("开始时间:", new object[]{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fffff")});
                List<DbParameter> lstParam = new List<DbParameter>();
                string sql_update = DBHelper.GenerateUpdateSql<WCS_OPCITEM>(entity, "wcs_opcitem", "stationno", "MySql.Data.MySqlClient", out lstParam);//System.Data.MySqlClient
                int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql_update, lstParam.ToArray());
                //stalog.Info("结束时间:",  new object[]{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fffff")});
                return i > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 生成路径
        /// </summary>
        /// <returns></returns>
        public bool InsertConveryRoute(string fromstation, string to_station, string equipmentnumber, string tasktype, ref string msg)
        {
            try
            {
                msg = "";
                List<DbParameter> lstParam = new List<DbParameter>();
                lstParam.Add(new MySqlParameter { Value = WareHouseID, ParameterName = "i_warehouseid", Direction = ParameterDirection.Input });
                lstParam.Add(new MySqlParameter { Value = fromstation, ParameterName = "i_fromstation", Direction = ParameterDirection.Input });
                lstParam.Add(new MySqlParameter { Value = to_station, ParameterName = "i_tostation", Direction = ParameterDirection.Input });
                lstParam.Add(new MySqlParameter { Value = equipmentnumber, ParameterName = "i_equipmentnumber", Direction = ParameterDirection.Input });
                lstParam.Add(new MySqlParameter { Value = tasktype, ParameterName = "i_type", Direction = ParameterDirection.Input });
                lstParam.Add(new MySqlParameter { Value = 0, ParameterName = "o_result", Direction = ParameterDirection.Output });
                lstParam.Add(new MySqlParameter { Value = "", ParameterName = "o_msg", Direction = ParameterDirection.Output, Size = 200 });
                DataAccessFactory.Instance.ExecuteNonQuery(CommandType.StoredProcedure, "wcs_addroute_p", lstParam.ToArray());
                if (lstParam[5].Value != null)
                {
                    msg = lstParam[6].Value.ToString();
                    return int.Parse(lstParam[5].Value.ToString()) > 0;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return false;
        }
        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <param name="type"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public DataTable GetEquipment(string type, string orderby)
        {
            try
            {
                DataTable dt = new DataTable();
                DataSet ds = DataAccessFactory.Instance.ExecuteDataSet("select equipmentnumber,equipmentid from Equipment where typecode='" + type + "' order by " + orderby, CommandType.Text, null);
                if (ds != null && ds.Tables.Count > 0)
                    dt = ds.Tables[0];
                return dt;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        /// <summary>
        /// 输送机设备初始化
        /// </summary>
        /// <returns></returns>
        public bool ConveryInit()
        {
            try
            {
                DataTable dt = GetWCS_OPCItem();
                lst = ConvertToList(dt);
                // scanBLL.AddScanConfigure();  //获取扫码器配置
                string error = "";
                stalog.Info("区域：{0}，输送机初始化...", new object[] { ZoneCode });
                plc.InitData(lst, ref error);
                stalog.Info("区域：{0}，输送机初始化完毕!", new object[] { ZoneCode });
                stalog.Info("区域：{0}，输送机准备启动...", new object[] { ZoneCode });
                //Thread thread1 = new Thread(new ThreadStart(TimeScan_H));
                //thread1.Start();
                //QueueSpeech.Start();
                // plc.Run(1);
                for (int i = 1; i <= (ZoneCode == "HC" ? 10 : 10); i++)
                {
                    plc.Run(i);
                }

                stalog.Info("区域：{0}，输送机准备启动完成...", new object[] { ZoneCode });
                smartBLL.SmartInit();
            }
            catch (Exception ex)
            {
                stalog.Info("区域：{0}，输送机启动时发生异常，", ex);
                //throw ex;
            }
            return true;
        }
        private List<ConveryEntity> ConvertToList(DataTable dt)
        {
            if (dt == null || dt.Rows.Count <= 0)
                throw new Exception();
            lst = new List<ConveryEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["belong"].ToString() != "0")
                {
                    ConveryEntity ci = new ConveryEntity();
                    ci.C_TaskInfo = new ConveryTaskInfo();
                    ci.StationNo = dr["stationno"].ToString();
                    ci.stationName = dr["itemname"].ToString();

                    ci.Key_ip = dr["userid"].ToString();
                    ci.DBAddress = int.Parse(dr["objects"].ToString().Split(',')[0]);
                    ci.ScanDBAddress = int.Parse(dr["objects"].ToString().Split(',')[1]);
                    ci.length = int.Parse(dr["signaltype"].ToString().Split(',')[0]);
                    ci.Scanlength = int.Parse(dr["signaltype"].ToString().Split(',')[1]);
                    ci.value = int.Parse(dr["value"].ToString().Split(',')[0]);
                    ci.Scanvalue = int.Parse(dr["value"].ToString().Split(',')[1]);
                    ci.StationType = int.Parse(dr["StationType"].ToString());
                    ci.LocationX = int.Parse(dr["LocationX"].ToString());
                    ci.LocationY = int.Parse(dr["LocationY"].ToString());
                    ci.Width = int.Parse(dr["Width"].ToString());
                    ci.Height = int.Parse(dr["Height"].ToString());
                    ci.Belong = dr["belong"].ToString();
                    ci.config = dr["groupname"].ToString();
                    ci.C_TaskInfo.datatype = dr["datetype"].ToString();
                    ci.C_TaskInfo.stationno = ci.StationNo;
                    ci.C_TaskInfo.stationtype = ci.StationType;
                    ci.C_TaskInfo.ZoneCode = dr["ZoneCode"].ToString();
                    ci.C_TaskInfo.zone = dr["zone"].ToString();
                    ci.C_TaskInfo.mode = dr["field3"].ToString();
                    if (ci.C_TaskInfo.mode == "2")
                    {
                        ci.ItemCodeScanvalue = int.Parse(dr["value"].ToString().Split(',')[2]);
                        ci.ItemCodeScanlength = int.Parse(dr["signaltype"].ToString().Split(',')[2]);
                    }
                    lst.Add(ci);
                }
            }
            return lst;
        }

        public void LEDSendInFO(String stationno, string msg)
        {
            string LEDnumber = "";
            switch (stationno)//对应的LED屏下发报警信息
            {
                case "1221":
                case "1277":
                    LEDnumber = LEDStation[0];
                    break;
                case "2257":
                case "2201":
                    LEDnumber = LEDStation[1];
                    break;
            }
            if (LEDnumber != "")
            {
                led.send_Msg(LEDnumber, "alarm", stationno + "站台报警：" + msg);//对3号屏进行下发报警信息
            }
        }

        /// <summary>
        /// 输送机业务逻辑处理
        /// </summary>
        /// <param name="si"></param>
        private void DoWork(object task)
        {
            try
            {
                ConveryTaskInfo si = task as ConveryTaskInfo;

                STACommand cmd = STACommand.ReWrite;
                int index = 0;
                if ((task != null && ((si.stationtype > 0 || si.datatype == "SCAN")
                    && (si.stationno == si.tostation.ToString()) && si.tasknum >= 1000))||si.stationtype ==16
                    || ((si.stationno == "2228" || si.stationno == "2229"
                    || si.stationno == "2363" || si.stationno == "2367" || si.stationno == "3201" || si.stationno == "3202"|| si.stationno == "2359" || si.stationno == "2401")))
                {
                    bool b_flag = false;
                    string barcode = string.Empty;
                    string barcode1 = string.Empty;
                    string scan_itemcode1 = string.Empty;
                    string scan_itemcode2 = string.Empty;
                    string itemcode1 = string.Empty;
                    string itemcode2 = string.Empty;
                    String[] StaStationInfo = plc.ReadStaInfo(si.stationno);
                    string StaStationbarcode = "";
                    string[] temp = new string[2];
                    string[] TaskInfo = new string[8];
                    TaskInfo[0] = si.stationno.ToString();
                    string LEDnumber = "";
                    for (int i = 1; i < 7; i++)
                    {
                        TaskInfo[i] = StaStationInfo[i];
                    }
                    string checkinfo = si.checkinfo.ToString();
                    string checkinfo1 = string.Empty;
                    barcode = si.barcode;
                    barcode1 = si.barcode1;
                    string msg = "";
                    int result = 0;
                    string tostation = string.Empty;
                    bool outemptyflag = false;
                    string taskno = string.Empty;
                    if (si.stationtype == 16&&si.tasknum==0&&si.gooodstype==0)
                    {
                        si.tasknum = 1000;
                        outemptyflag = true;                    
                    }
                    /*#region 判断1905 当起始站台为空时 可从库内出一盘需要挑选的托盘
                    if (si.stationno == "2533" || si.stationno == "2536" || si.stationno == "2540" || si.stationno == "2596" || si.stationno == "2597")
                    {
                        //string[] StationInfo2308 = plc.ReadStaInfo("2308");
                        if (StaStationInfo[4] == "0" && StaStationInfo[1] == "0" && StaStationInfo[8] == "100")
                        {
                            taskno = string.Empty;
                            if (CheckExistsTask("2526", ref taskno))
                            {
                                if (UpdateTaskRunstatus(taskno))
                                {
                                    cmd = STACommand.ClearToStation;
                                    WriteStationInfo(cmd, new string[2] { si.stationno, "2" }, si.stationno, 2, 2);
                                    ShowConveryLog("WriteInfo", "挑选站台：" + si.stationno + "空闲,预约任务:" + taskno + "出库挑选!");
                                }
                            }
                            return;
                        }
                        if (si.stationno != si.tostation.ToString())
                        {
                            return;
                        }
                    }
                    #endregion*/

                    #region 判断2394, 2395, 2396, 2397,2398,2400,2558,2559的托盘数量<8可出常温3托盘
                    if (si.stationno == "3201" || si.stationno == "3202" || si.stationno == "2363" || si.stationno == "2367"||si.stationno == "2401" || si.stationno == "2359")
                    {
                        int buffercount = 0;
                        int needcount = 0;
                        //string[] StationInfo2401 = plc.ReadStaInfo("2401");
                        buffercount = CheckExistsTask("2561","2360");
                        needcount = GetCellExecteCount("2561");
                        if (buffercount < needcount && CheckExistsTask("2360", "P", ref taskno))
                        {
                            if (StaStationInfo[4] == "0" && StaStationInfo[1] == "0")//&& (StaStationInfo[8] == "100")
                            {
                                if (CheckExistsTask("2360", "P", ref taskno))
                                {
                                    if (UpdateTaskRunstatus(taskno))
                                    {
                                        cmd = STACommand.ClearToStation;
                                        WriteStationInfo(cmd, new string[2] { si.stationno, "2" }, si.stationno, 2, 2);
                                        ShowConveryLog("WriteInfo", "OCV缓存站台：" + si.stationno + "空闲,到目标地址2561与常温3可执行出库任务的WCS任务数:" + buffercount + "个,小于设定的" + needcount + "个，预约任务:" + taskno + "常温3出库!");
                                    }
                                }
                                return;
                            }
                            if (si.stationno != si.tostation.ToString())
                            {
                                return;
                            }
                        }
                        else
                        {
                            #region 判断3201,3202,2363,2367 当起始站台为空时 可从库内出一盘常温3的托盘
                            if (si.stationno == "3201" || si.stationno == "3202" || si.stationno == "2363" || si.stationno == "2367"|| si.stationno == "2401" || si.stationno == "2359")
                            {
                                if (StaStationInfo[4] == "0" && StaStationInfo[1] == "0")//&& (StaStationInfo[8] == "100")
                                {
                                    if (CheckExistsTask("2360", "M", ref taskno))
                                    {
                                        if (UpdateTaskRunstatus(taskno))
                                        {
                                            cmd = STACommand.ClearToStation;
                                            WriteStationInfo(cmd, new string[2] { si.stationno, "2" }, si.stationno, 2, 2);
                                            ShowConveryLog("WriteInfo", "OCV缓存站台：" + si.stationno + "空闲,到目标地址2561与常温3可执行出库任务的WCS任务数:" + buffercount + "个,大于等于设定的" + needcount + "个，预约任务:" + taskno + "常温2出库!");
                                        }
                                    }
                                    return;
                                }
                                if (si.stationno != si.tostation.ToString())
                                {
                                    return;
                                }
                            }
                            #endregion
                        }
                    }
                    if (si.stationno == "2228" || si.stationno == "2229")
                    {
                        String[] StaStationInfo2228 = plc.ReadStaInfo("2228");
                        String[] StaStationInfo2229 = plc.ReadStaInfo("2229");
                        //2228\2229都空闲状态下，那么查询分容是否有库位，若分容有库位并且分容缓存库位有料，那么缓存位托盘移库到分容柜
                        if (StaStationInfo2228[1] == "0" && StaStationInfo2228[8] == "100" && StaStationInfo2229[1] == "0" && StaStationInfo2229[8] == "100")
                        {
                            string equipmentnumber = string.Empty;
                            int count = ExistsFREmptyLocation(ref equipmentnumber);
                            int buffer_count = ExistsBufferLocation(equipmentnumber);
                            if (count > 0 && buffer_count > 0)
                            {
                                if (UpdateBufferLocationOutflag(equipmentnumber, buffer_count))
                                {
                                    ShowConveryLog("WriteInfo", "站台：2228、2229空闲,分容缓存货位预约移库成功！！！");
                                    return;
                                }
                            }
                        }
                    }
                    #endregion
                    if (si.datatype == "SCAN")
                    {
                        tostation = GetItempalletTostation(si.barcode);
                        if (si.mode == "1")  //扫托盘条码  
                        {
                            si.scanbarcode = ReadScanbarcodeinfo(si.stationno, si.mode);
                            if (si.scanbarcode != si.barcode)
                            {
                                ShowConveryLog("WriteInfo", "扫码站台：" + si.stationno + ",托盘条码:" + barcode + "与扫码枪托盘条码:" + si.scanbarcode + "不一致");
                                return;
                            }
                            if (barcode == "ERROR")
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "非法!");
                                return;
                            }
                            if ((si.barcode == "" || string.IsNullOrEmpty(si.barcode)))
                            {
                                return;
                            }
                            if (si.stationno == tostation)
                            {
                                
                            }
                            else
                            {
                                if (si.stationtype != 1 && si.stationtype != 3&&si.gooodstype.ToString().StartsWith("1"))//空托盘初始化+拆装盘工位站台直接进行业务处理
                                {
                                    if (!string.IsNullOrEmpty(tostation))
                                    {
                                        cmd = STACommand.ClearToStation;
                                        WriteStationInfo(cmd, new string[2] { si.stationno, tostation }, si.stationno, 4, 2);
                                        ShowConveryLog("WriteInfo", "扫码站台：" + si.stationno + ",托盘条码" + barcode + "重新分配目标地址:" + tostation + "");
                                        return;
                                    }
                                    else
                                    {
                                        ShowConveryLog("WriteInfo", "扫码站台：" + si.stationno + ",托盘条码:" + barcode + "未记录目标地址!请人工更改目标地址!");
                                        return;
                                    }
                                }
                            }
                        }
                        else if (si.mode == "2")  //扫电芯条码
                        {
                            bool errorFlag = false;
                            string[] itemcodes = getItemcodeByPalltecode(si.barcode, ZoneCode);
                            string[] scanitemcodes = ReadScanbarcodeinfo(si.stationno, ZoneCode, si.mode);
                            si.scanitemcode1 = scanitemcodes[0];
                            si.scanitemcode2 = scanitemcodes[1];
                            if (itemcodes[0] != si.scanitemcode1 && !itemcodes[0].StartsWith("WCS"))
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + ",WMS绑盘记录中位置:" + ((LineCode == "L7" || LineCode == "L8") ? "1" : (ZoneCode == "HC" ? "17" : "13")) + "的电芯条码：" + itemcodes[0] + "与第一个扫码枪扫出条码:" + si.scanitemcode1 + "不一致!");
                                errorFlag = true;
                            }
                            if (itemcodes[1] != si.scanitemcode2 && !itemcodes[1].StartsWith("WCS"))
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + ",WMS绑盘记录中位置:" + ((LineCode == "L7" || LineCode == "L8") ? (ZoneCode == "HC" ? "32" : "24") : (ZoneCode == "HC" ? "16" : "12")) + "的电芯条码：" + itemcodes[1] + "与第二个扫码枪扫出条码:" + si.scanitemcode2 + "不一致!");
                                errorFlag = true;
                            }
                            if (errorFlag)
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "8888" }, si.stationno, 4, 2);
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "扫码检验失败!通知物流线报警!");
                                return;
                            }
                        }
                        else if (si.mode == "3") //工装扫码器
                        {
                            string scanInfo = string.Empty;
                            scanBLL.scanProcess(si.stationno, si.barcode, ref scanInfo);
                            if (scanInfo.Trim() != si.barcode.Trim())
                            {
                                ShowConveryLog("WriteInfo", "扫码站台：" + si.stationno + ",托盘条码:" + barcode + "与扫码枪托盘条码:" + si.scanbarcode + "不一致");
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "8888" }, si.stationno, 4, 2);
                                return;
                            }
                            if (barcode == "ERROR")
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "非法!");
                                return;
                            }
                            if ((si.barcode == "" || string.IsNullOrEmpty(si.barcode)))
                            {
                                return;
                            }
                            #region 工装扫码站台
                            if (si.stationtype == 9)
                            {
                                if (UpdateTaskRunstatus(si.tasknum.ToString()))
                                {
                                    cmd = STACommand.ClearToStation;
                                    WriteStationInfo(cmd, new string[2] { si.stationno, "1" }, si.stationno, 4, 2);
                                    ShowConveryLog("WriteInfo", "工装扫码站台：" + si.stationno + "扫码成功,将任务:" + si.tasknum + "改为可执行!");
                                }
                            }
                            #endregion
                        }
                        else if (si.mode == "4")//拍照
                        {
                            Dictionary<int, string> cellInfo = new Dictionary<int, string>();
                            bool photoFlag = photoBLL.startPhoto(si.stationno, si.barcode, ref cellInfo);//获取是否拍照成功
                            if (!photoFlag)
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + ",等待返回拍照结果!");
                                return;
                            }
                            if (cellInfo == null || cellInfo.Count == 0)
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "8888" }, si.stationno, 4, 2);
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + ",拍照失败!" + PhotoBLL.cellInfos[si.stationno].message);
                                PhotoBLL.cellInfos[si.stationno] = new Result(); //检验失败后 清空拍照信息
                                return;
                            }
                            Dictionary<int, string> itemCodes = new Dictionary<int, string>();

                            if (!getItemCodes(si.barcode, ref itemCodes))
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "WMS内无数据!");
                                return;
                            }
                            if (itemCodes.Count != cellInfo.Count)
                            {
                                ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "WMS内数据数量:" + itemCodes.Count + "与拍照数据数量:" + cellInfo.Count + "不一致!");
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "8888" }, si.stationno, 4, 2);
                                return;
                            }
                            for (int i = 1; i <= itemCodes.Count; i++)
                            {
                                if (itemCodes[i] != cellInfo[i] && itemCodes[i].Substring(0, 3) != "WCS")
                                {
                                    ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "WMS内第" + i + "位置电芯条码:" + itemCodes[i] + "与拍照电芯条码:" + cellInfo[i] + "不一致!");
                                    WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "8888" }, si.stationno, 4, 2);
                                    PhotoBLL.cellInfos[si.stationno] = new Result(); //检验失败后 清空拍照信息
                                    return;
                                }
                            }
                        }
                    }
                    if ((si.barcode == "" || string.IsNullOrEmpty(si.barcode) || si.barcode == "0" || barcode == "ERROR") && si.stationtype != 1 && si.stationtype != 6 && si.stationtype != 16)
                    {
                        ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "非法!");
                        return;
                    }
                    bool TrayModeCheck = true;
                   /* for (int i = 0; i < TrayMode.Length; i++)
                    {
                        if (si.barcode.Contains(TrayMode[i]))
                        {
                            TrayModeCheck = true;
                        }
                    }*/

                    if (si.stationtype == 16 && si.fromstation != 0 && si.gooodstype == 0)
                    {
                        WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "0" }, si.stationno, 0, 2);
                        WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "0" }, si.stationno, 4, 2);
                        return;
                    }

                    if (si.stationtype == 16 && si.gooodstype == 1)
                    {
                        if (si.stationno == "1673")
                        {
                            foreach (var station in oldTostation1673)
                            {
                                String[] stationinfo = plc.ReadStaInfo(station);
                                if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                                {
                                    return;
                                }
                                if (stationinfo[1] != "0" || stationinfo[4] != "0" || stationinfo[8] != "100")
                                {
                                    return;
                                }
                            }
                        }
                    }
                    if (si.stationtype == 1)
                    {
                        if (!TrayModeCheck)
                        {
                            ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "不是该系统当前生产的托盘,请检查配置文件中TrayMode的值!");
                            return;
                        }
                    }
                    if (si.stationtype == 1 && si.tasknum == 1000 && si.gooodstype == 0)
                    {
                        BLLBase.modeTime = DateTime.Now;
                        //if (BLLBase.Mode == 0)
                        //{
                        //    ShowConveryLog("WriteInfo", "站台：" + si.stationno + "投入托盘:" + si.barcode + "时,未选择模式!不允许投入！");
                        //    return;
                        //}
                        //else
                        //    si.gooodstype = BLLBase.Mode;
                    }

                    #region 产生入库任务前 判断取货口是否被占用 适用于双货叉
                    if (si.stationno == "1507")
                    {
                        int useStationCount = 0;  //被占用的站台数量
                        foreach (var station in oldTostation1507)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] == "0" && stationinfo[4] == "0" && stationinfo[8] == "100")
                            {
                                si.pickStation = station;
                                break;
                            }
                            else
                            {
                                useStationCount++;
                            }
                        }
                        if (useStationCount == oldTostation1507.Count())
                        {
                            ShowConveryLog("WriteInfo", "站台：" + si.stationno + ",托盘条码:" + barcode + "申请入库，取货口均被占用!");
                            return;
                        }
                    }
                    #endregion
                    //A区拆盘后 空托盘分配站台
                    if (si.stationno == "1758" && si.gooodstype == 11)
                    {
                        String[] StaStationInfo_1673 = plc.ReadStaInfo("1673");
                        if (StaStationInfo_1673[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                        {
                            return;
                        }
                        if (StaStationInfo_1673[1] == "0" && StaStationInfo_1673[4] == "0" && (StaStationInfo_1673[8] == "100" ))
                        {
                            //WriteStationInfo(STACommand.ClearToStation, new string[2] { "1673", "1" }, "1673", 2, 2);
                            //WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, "1673" }, si.stationno, 4, 2);
                            //UpdateItempalletTostation(si.barcode, "1673");
                            //ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + "1673" + "");
                            //return;
                        }
                    }
                    #region 1007空托盘完成任务站台  当任务号为1234时表示已完成任务处理  可直接分配
                    if ((si.stationno == "1007") && si.gooodstype == 11 && si.tasknum == 1234)
                    {
                        foreach (var station in oldTostation1007)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] == "0" && stationinfo[4] == "0" && (stationinfo[8] == "100" || stationinfo[8] == "0"))
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, station }, si.stationno, 4, 2);
                                UpdateItempalletTostation(si.barcode, station);
                                ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + station + "");
                                break;
                            }
                        }
                        return;
                    }
                    #endregion
                    //分配拔钉 xwd
                    if ((si.stationno == "1710") && TaskInfo[3] == "12")
                    {
                        foreach (var station in oldTostation1710)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] != "0" || stationinfo[4] != "0" || stationinfo[8] != "100")
                            {
                                return;
                            }
                        }
                    }

                    //插钉站台分配1670 xwd
                    if ((si.stationno == "1092" || si.stationno == "1093" )&& si.tasknum==9999 && si.gooodstype == 12)
                    {
                        if (arriveTimeCD.Where(p => p.Value.barcode == si.barcode).Count() == 0)
                        {
                            arriveTimeCD.AddOrUpdate(si.stationno, new ArriveInfo() { barcode = si.barcode, dateTime = DateTime.Now, flag = false }, (k, v) => new ArriveInfo() { barcode = si.barcode, dateTime = DateTime.Now, flag = false });
                        }
                        else
                        {
                            arriveTimeCD[si.stationno].flag = false;
                        }
                        var dicSort = from info in arriveTimeCD where info.Value.flag == false orderby info.Value.dateTime select info;

                        if (dicSort.FirstOrDefault().Key != si.stationno)
                            return;
                        String[] stationinfo = plc.ReadStaInfo("1670");
                        if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                        {
                            return;
                        }
                        if (stationinfo[1] != "0" || stationinfo[4] != "0" || stationinfo[8] != "100")
                        {
                            return;
                        }
                    }
                    //分配插钉工位 xwd
                    if ((si.stationno == "1652" || si.stationno == "1643") && si.gooodstype == 12&&si.tasknum==1234)
                    {
                        if (arriveTimeCD.Where(p => p.Value.barcode == si.barcode).Count() == 0)
                        {
                            arriveTimeCD.AddOrUpdate(si.stationno, new ArriveInfo() { barcode = si.barcode, dateTime = DateTime.Now, flag = false }, (k, v) => new ArriveInfo() { barcode = si.barcode, dateTime = DateTime.Now, flag = false });
                        }
                        else
                        {
                            arriveTimeCD[si.stationno].flag = false;
                        }
                        var dicSort = from info in arriveTimeCD where info.Value.flag == false orderby info.Value.dateTime select info;

                        if (dicSort.FirstOrDefault().Key != si.stationno)
                            return;
                        foreach (var station in tostationCD)
                        {
                            arriveTime[si.stationno].flag = true;
                            WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                            WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, station }, si.stationno, 4, 2);
                            UpdateItempalletTostation(si.barcode, station);
                            ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + station + "");
                            break;
                        }
                        return;
                    }
                    // 1624拆盘缓存站台 xwd
                    if (si.stationno == "1624" && si.gooodstype == 12 )
                    {
                        foreach (var station in oldTostation1624)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] == "0" && stationinfo[4] == "0" && (stationinfo[8] == "100"))
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, station }, si.stationno, 4, 2);
                                UpdateItempalletTostation(si.barcode, station);
                                ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + station + "");
                                break;
                            }
                        }
                        return;
                    }
                    //拆盘缓存站台
                    if (si.stationno == "1670" && si.gooodstype == 12 && si.tasknum == 1234)
                    {
                        foreach (var station in oldTostation1670)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] == "0" && stationinfo[4] == "0" && stationinfo[8] == "100")
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, station }, si.stationno, 4, 2);
                                UpdateItempalletTostation(si.barcode, station);
                                ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + station + "");
                                break;
                            }
                        }
                        return;
                    }
                    //OCV2测试完成
                    /* if (si.stationno == "2285" && si.gooodstype == 2 && si.tasknum == 9999)
                     {
                         String[] stationinfo = plc.ReadStaInfo("2213");
                         if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                         {
                             return;
                         }
                         if (stationinfo[1] != "0" || stationinfo[4] != "0" || stationinfo[8] != "100")
                         {
                             return;
                         }
                     }*/

                    //分容段
                    #region 2102分配分容组盘站台
                    if (si.stationno == "2102" && si.gooodstype == 11 && si.tasknum == 1234)
                    {
                        foreach (var station in oldTostation2102)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] == "0" && stationinfo[4] == "0" && (stationinfo[8] == "100"))
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, station }, si.stationno, 4, 2);
                                UpdateItempalletTostation(si.barcode, station);
                                ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + station + "");
                                break;
                            }
                        }
                        return;
                    }
                    #endregion
                    #region 2072分配分容组盘站台
                    if (si.stationno=="2072")
                    { 
                        
                    }
                    if (si.stationno == "2072" && si.gooodstype == 11 && si.tasknum == 1234)
                    {
                        foreach (var station in oldTostation2072)
                        {
                            String[] stationinfo = plc.ReadStaInfo(station);
                            if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (stationinfo[1] == "0" && stationinfo[4] == "0" && (stationinfo[8] == "100"))
                            {
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                WriteStationInfo(STACommand.ClearToStation, new string[2] { si.stationno, station }, si.stationno, 4, 2);
                                UpdateItempalletTostation(si.barcode, station);
                                ShowConveryLog("WriteInfo", "站台:" + si.stationno + ",托盘: " + si.barcode + "重新分配目标地址:" + station + "");
                                break;
                            }
                        }
                        return;
                    }
                    #endregion


                    if (ocvMsaStatus)
                    {
                        if (si.stationno == "1617" && ocvMsa.Count == 0)
                        {
                            if (!ocvMsa.ContainsKey(si.barcode))
                                ocvMsa.Add(si.barcode, si.stationno);
                            tostation = "1618";
                            UpdateItempalletTostation(si.barcode, tostation);
                            cmd = STACommand.ClearToStation;
                            WriteStationInfo(cmd, new string[2] { si.stationno, tostation }, si.stationno, 4, 2);
                            ShowConveryLog("WriteInfo", "OCV站台：" + si.stationno + ",开始MSA,托盘:" + barcode);
                            return;
                        }
                        if (si.stationno == "1618")
                        {
                            if (ocvMsa.ContainsKey(si.barcode))
                            {
                                tostation = "1108";
                                UpdateItempalletTostation(si.barcode, tostation);
                                cmd = STACommand.ClearToStation;
                                WriteStationInfo(cmd, new string[2] { si.stationno, tostation }, si.stationno, 4, 2);
                                ShowConveryLog("WriteInfo", "OCV站台：" + si.stationno + ",开始MSA,托盘:" + barcode);
                                return;
                            }
                        }
                    }

                    //lock (objLock)
                    //{
                    DateTime dateTime = DateTime.Now;
                    ShowConveryLog("Time", "站台:" + si.stationno + ",托盘:" + si.barcode + "开始业务处理!时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                    if (si.stationno == "2308")
                    { }
                    if (GettaskInfo(WareHouseID, si.barcode, si.barcode1, si.stationno, si.stationtype.ToString(), si.gooodstype.ToString(), si.zone, si.tasknum.ToString(), checkinfo, "", ref msg, ref result))
                    {
                        if (si.stationno == "2123" && si.gooodstype == 0 && si.fromstation == 0 && CheckExistsWCS_SubTask("2219", ref taskno))
                        {
                            cmd = STACommand.ClearToStation;
                            WriteStationInfo(cmd, new string[2] { si.stationno, "2" }, si.stationno, 2, 2);
                            ShowConveryLog("WriteInfo", "分容复测空盘缓存站台：" + si.stationno + "空闲,已预约任务:" + taskno + "空盘出库到2219!");
                            return;
                        }
                        if (led.DLed.ContainsKey(si.stationno) && LedString != LedStringOld)
                        {
                            //对LED屏进行下发信息。
                            LEDSendInFO(si.stationno, msg);
                        }
                        if (outemptyflag) return;
                        TaskInfo = ConvertToTaskInfo(TaskInfo, msg);
                        ShowConveryLog("WriteInfo", msg);
                        if (result == 1 || result == 2)
                            b_flag = true;
                        else
                        {
                            b_flag = false;
                            if (result > 2 && result < 7)
                            {
                                string[] TaskTemp = new string[2];
                                TaskTemp[0] = TaskInfo[0];
                                TaskTemp[1] = result.ToString();
                                index = 4;
                                cmd = STACommand.ClearToStation;
                                if (WriteStationInfo(cmd, TaskTemp, si.stationno, index, 2))//写入PLC信息
                                {
                                    ShowConveryLog("WriteInfo", "站台：" + si.stationno + msg + "写入错误信息到PLC成功！任务号" + TaskTemp[0] + "错误编码：" + result);
                                }
                                else
                                {
                                    ShowConveryLog("WriteInfo", "站台：" + si.stationno + msg + "写入错误信息到PLC失败！任务号" + TaskTemp[0] + "错误编码：" + result);
                                }
                            }
                            //LEDSendInFO(si.stationno, msg);//对LED屏进行下发信息。
                        }
                        if ((result == 0 || result == 2))
                        {
                            ledmsg = " 托盘号：" + TaskInfo[2] + TaskInfo[7];
                        }
                        if (!stationDSalarm.ContainsKey(si.stationno))
                        {
                            stationDSalarm.Add(si.stationno, 0);
                        }
                        else
                        {
                            stationDSalarm[si.stationno] = 0;

                        }
                    }
                    else
                    {
                        if (msg.Length > 0)
                        {
                            ShowConveryLog("WriteInfo", msg);
                        }
                        //用于报警：出库任务长时间未获取到任务。
                        if (si.tasknum.ToString() == "1000" && si.gooodstype.ToString() == "0" && si.barcode.ToString() == "")
                        {
                            if (!stationDSalarm.ContainsKey(si.stationno))
                            {
                                stationDSalarm.Add(si.stationno, 0);
                            }
                            else if (stationDSalarm[si.stationno] > Convert.ToInt32(WaitCount))
                            {
                                //LEDSendInFO(si.stationno, "出库站台长时间未获取到任务");
                            }
                            stationDSalarm[si.stationno] = stationDSalarm[si.stationno] + 1;
                        }
                        else
                        {
                            //LEDSendInFO(si.stationno, msg);//对LED屏进行下发信息。
                        }
                    }
                    ShowConveryLog("Time", "站台:" + si.stationno + ",托盘:" + si.barcode + "结束业务处理!时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "。时间差:" + (DateTime.Now - dateTime).TotalMilliseconds);
                    if (b_flag)
                    {
                        for (int i = 0; i < TaskInfo.Length; i++)
                        {
                            if (TaskInfo[i] == null || TaskInfo[i].Equals(""))
                            {
                                TaskInfo[i] = "0";
                            }
                        }
                        #region 当其可去站台包含站台类型为16的站台时  优先查是否有从库内出库的空托盘任务
                        //B区异常口投盘后
                        if (si.stationno == "1300" && TaskInfo[5] == "1305" && TaskInfo[3] == "1")
                        {
                            String[] StaStationInfo_1455 = plc.ReadStaInfo("1455");
                            if (StaStationInfo_1455[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                            {
                                return;
                            }
                            if (StaStationInfo_1455[1] == "0" && StaStationInfo_1455[4] == "0" && StaStationInfo_1455[8] == "100")
                            {
                                //得到1455还需要的空托盘数量
                                int count = getNeedBufferCount("1455");
                                if (count > 0)
                                {
                                    TaskInfo[5] = "1455";
                                    WriteStationInfo(STACommand.ClearToStation, new string[2] { TaskInfo[5], "1" }, TaskInfo[5], 2, 2);
                                }
                            }
                            else
                            {
                                String[] StaStationInfo_1502 = plc.ReadStaInfo("1502");
                                String[] StaStationInfo_1504 = plc.ReadStaInfo("1504");
                                if (StaStationInfo_1502[0] == "0" || StaStationInfo_1504[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                                {
                                    return;
                                }
                                if (StaStationInfo_1502[1] == "0" && StaStationInfo_1504[1] == "0"
                                    && StaStationInfo_1502[8] == "100" && StaStationInfo_1504[8] == "100")
                                {
                                    TaskInfo[5] = "1509";
                                }
                            }
                        }
                        //D区挑选剩余空盘后
                        if (si.stationno == "2045" && TaskInfo[5] == "1932" && TaskInfo[3] == "1")
                        {
                            if (!TrayModeCheck)
                            {
                                TaskInfo[5] = "1809";
                            }
                        }

                        if ((si.stationno == "2308") && si.gooodstype == 12 && (TaskInfo[5] == "2901" || TaskInfo[5] == "2902"))
                        {
                            foreach (var station in oldTostation2308)
                            {
                                String[] stationinfo = plc.ReadStaInfo(station);
                                string tostation1 = station;
                                TaskInfo[5] = si.stationno;
                                if (stationinfo[0]=="0")
                                {
                                    return;
                                }
                                if (stationinfo[1] == "0" && (stationinfo[4] == "0"||stationinfo[4] == "2") && stationinfo[8] == "100")
                                {
                                    if (station == "2314")
                                        tostation1 = "2901";
                                    else if (station =="2318")
                                        tostation1 = "2902";
                                    TaskInfo[5] = tostation1;
                                    WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                    break;
                                }
                            }
                        }
                        //E区拆盘或E区异常口投入空盘
                        if ((si.stationno == "2236" || si.stationno == "2221" || si.stationno == "2217") && TaskInfo[5] != "2236" && TaskInfo[3] == "1")
                        {
                            if (!TrayModeCheck)
                            {
                                TaskInfo[5] = "2236";
                            }
                            else
                            {
                                foreach (var station in oldTostation2202)
                                {
                                    String[] stationinfo = plc.ReadStaInfo(station);
                                    if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                                    {
                                        return;
                                    }
                                    if (stationinfo[1] == "0" && stationinfo[4] == "0" && stationinfo[8] == "100")
                                    {
                                        //得到station还需要的空托盘数量
                                        int count = getNeedBufferCount(station);
                                        if (count > 0)
                                        {
                                            TaskInfo[5] = station;
                                            WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        #endregion

                        if (si.stationno == "2604" && TaskInfo[3] == "12")
                        {
                            TaskInfo[5] = si.stationno;
                            foreach (var station in oldTostation2604)
                            {
                                String[] stationinfo = plc.ReadStaInfo(station);
                                if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                                {
                                    return;
                                }
                                if (stationinfo[1] == "0" && stationinfo[4] == "0" && stationinfo[8] == "100")
                                {
                                    WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                    TaskInfo[5] = station;
                                    break;
                                }
                            }
                        }
                        //B区拆盘
                        if (si.stationno == "1408" && TaskInfo[3] == "2" && TaskInfo[5] != "1300")
                        {
                            TaskInfo[1] = "1234";
                            TaskInfo[5] = si.stationno;
                            foreach (var station in oldTostation1408)
                            {
                                String[] stationinfo = plc.ReadStaInfo(station);
                                if (stationinfo[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                                {
                                    return;
                                }
                                if (stationinfo[1] == "0" && stationinfo[4] == "0" && stationinfo[8] == "100")
                                {
                                    WriteStationInfo(STACommand.ClearToStation, new string[2] { station, "1" }, station, 2, 2);
                                    TaskInfo[5] = station;
                                    break;
                                }
                            }
                        }
                        //B区拆盘完成后
                        if (si.stationno == "1414" && TaskInfo[5] == "1416" && TaskInfo[3] == "1")
                        {
                            if (!TrayModeCheck)
                            {
                                TaskInfo[5] = "1300";
                            }
                        }
                        if (si.stationno == "1411" && TaskInfo[5] == "1416" && TaskInfo[3] == "1")
                        {
                            if (!TrayModeCheck)
                            {
                                TaskInfo[5] = "1300";
                            }
                            else
                            {
                                String[] StaStationInfo_1417 = plc.ReadStaInfo("1417");
                                if (StaStationInfo_1417[0] == "0")  //当站台号为0时  认为没有读取到PLC数据
                                {
                                    return;
                                }
                                if (StaStationInfo_1417[1] == "0" && StaStationInfo_1417[4] == "0" && StaStationInfo_1417[8] == "100")
                                {
                                    TaskInfo[5] = "1417";
                                    WriteStationInfo(STACommand.ClearToStation, new string[2] { TaskInfo[5], "1" }, TaskInfo[5], 2, 2);
                                }
                            }
                        }
                        if (si.stationno == "2285" && TaskInfo[5] == "2214")
                        {
                            WriteStationInfo(STACommand.ClearToStation, new string[2] { "2213", "1" }, "2213", 2, 2);
                        }

                        #region 产生入库任务后 分配取货口
                        if (si.stationno == "1512")
                        {
                            //TaskInfo[5] = si.pickStation;
                            WriteStationInfo(STACommand.ClearToStation, new string[2] { si.pickStation, "1" }, si.pickStation, 2, 2);
                        }
                        #endregion

                        ShowConveryLog("WriteInfo", "站台:" + TaskInfo[0] + ",任务号:" + TaskInfo[1] + ",托盘条码:" + TaskInfo[2] + ",货物类型:" + TaskInfo[3] + ",起始地址:" + TaskInfo[4] + ",目标地址:" + TaskInfo[5]);

                        #region  更新托盘表中托盘目标地址
                        if (TaskInfo[5] != "1" && TaskInfo[5] != si.stationno && TaskInfo[5] != "0")
                        {
                            if (!UpdateItempalletTostation(TaskInfo[2], TaskInfo[5]))
                            {
                                ShowConveryLog("WriteInfo", "更新Itempallet表中托盘:'" + TaskInfo[2] + "'的目标地址失败,请检查该托盘是否初始化!");
                                return;
                            }
                        }
                        if (TaskInfo[5] == "1")
                        {
                            UpdateItempalletTostation(TaskInfo[2], "");
                        }
                        #endregion

                        cmd = STACommand.ReWrite;
                        if (WriteStationInfo(cmd, TaskInfo, si.stationno, 0, 22))
                        {
                            ShowConveryLog("Info", "站台：" + si.stationno + msg + "写入PLC成功！站台号：" + TaskInfo[0]);
                            Thread.Sleep(500);
                        }
                        else
                        {
                            ShowConveryLog("Info", "站台：" + si.stationno + msg + "写入PLC失败！站台号：" + TaskInfo[0]);
                        }
                    }
                    else
                    {
                        ShowConveryLog("WriteInfo", "站台:" + TaskInfo[0] + ",任务号:" + TaskInfo[1] + ",托盘条码:" + TaskInfo[2] + ",货物类型:" + TaskInfo[3] + ",起始地址:" + TaskInfo[4] + ",目标地址:" + TaskInfo[5]);
                    }
                    // }
                }
            }

            catch (Exception ex)
            {
                stalog.Info("输送机业务处理异常", ex);
            }
        }

        /// <summary>
        /// 写入命令
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="StationInfo"></param>
        /// <param name="stationum"></param>
        /// <param name="index"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public bool WriteStationInfo(STACommand cmd, string[] StationInfo, string stationum, int index, int length)
        {
            return plc.Write(cmd, StationInfo, stationum, index, length);
        }
        public bool WriteScanInfo(string ScanInfo, string stationum)
        {
            return plc.WriteScanInfo(ScanInfo, stationum);
        }
        public bool WriteStationInfo(string[] StationInfo, string stationum)
        {
            ConveryEntity si = lst.Find(
                delegate (ConveryEntity ss)
                {
                    return ss.StationNo == stationum;
                });
            if (si != null)
            {
                return WriteStationInfo(STACommand.ReWrite, StationInfo, stationum, si.value, si.length);
            }
            return false;
        }
        /// <summary>
        /// 读取站台信息
        /// </summary>
        /// <param name="station"></param>
        /// <returns></returns>
        public string[] ReadStationInfo(string station)
        {
            return plc.ReadPLCInfo(station);
        }
        public string[] ReadStationInfoByClent(string station)
        {
            return plc.ReadStationInfoByClent(station);
        }
         public string[] ReadScanbarcodeinfo(string stationno, string zonecode, string mode)
         {
             return plc.ReadBarcodeplcInfo(stationno, zonecode, mode);
         }
        public string ReadScanbarcodeinfo(string stationno, string mode)
        {
            return plc.ReadscanplcInfo(stationno);
        }

        /// <summary>
        /// 任务转换
        /// </summary>
        /// <param name="TaskInfo"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string[] ConvertToTaskInfo(string[] TaskInfo, string msg)
        {
            try
            {
                if (string.IsNullOrEmpty(msg))
                    throw new Exception(string.Format("任务信息为空"));
                string[] strTemp = msg.Split(';');//分解结果

                for (int i = 0; i < strTemp.Length; i++)
                {
                    if (strTemp[i] != null)
                    {

                        string str = strTemp[i].ToString().Substring(0, 2);

                        switch (str)
                        {
                            case "TN": TaskInfo[1] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                            //任务号
                            case "PN": TaskInfo[2] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                            //托盘号1

                            case "GS": TaskInfo[3] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                            //货物类型
                            case "FS": TaskInfo[4] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                            //起始站台
                            case "DS": TaskInfo[5] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                            //目标站台
                            case "XS": TaskInfo[6] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                            //旋转
                            case "er": TaskInfo[7] = strTemp[i].ToString().Substring(strTemp[i].ToString().LastIndexOf(":") + 1, strTemp[i].ToString().Length - strTemp[i].ToString().LastIndexOf(":") - 1); break;
                                //错误信息
                        }
                    }
                }
                return TaskInfo;
            }
            catch (Exception ex)
            {
                throw new Exception("任务信息转换失败，具体信息如下:" + ex.Message.ToString());
            }
        }

        /// <summary>
        /// 日志显示
        /// </summary>
        /// <param name="type"></param>
        /// <param name="msg"></param>
        public void ShowConveryLog(string type, string msg)
        {
            string stationlogkey = DateTime.Now.ToString("yyyyMMddHH");  //2021092401
            if (!string.IsNullOrEmpty(msg) && msg.Length > 7)//判断长度是否大于7，否则直接记录日志（避免报异常）
            {
                if (type == "WriteInfo")
                    stationlogkey = msg;
                else
                    stationlogkey = msg;
                if (type == "WriteInfo")
                {
                    var converyMsgString = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                    WebSocketHelper.SendMsgToRemotePoint("ConveryMsg" + converyMsgString);
                }
                //查看是否有该键存在，不存在则进行添加，然后发送
                if (!stationlog.ContainsKey(stationlogkey))
                {
                    stationlog.Add(stationlogkey, msg);
                    if (ShowLogMsg != null)
                    {
                        if (type == "Time")
                        {
                            staTimelog.Info(msg);
                        }
                        else
                        {
                            ShowLogMsg(type, msg);
                            stalog.Info(msg);
                        }
                    }
                }
                //如果存在，则判断是否存在相同值，若相同值，则不发送，不相同则发送，并记录
                else if (stationlog[stationlogkey] != msg)
                {
                    if (ShowLogMsg != null)
                    {
                        if (type == "Time")
                        {
                            staTimelog.Info(msg);
                        }
                        else
                        {
                            ShowLogMsg(type, msg);
                            stalog.Info(msg);
                        }
                    }
                    stationlog[stationlogkey] = msg;
                }
            }
            else
            {
                if (ShowLogMsg != null)
                {
                    ShowLogMsg(type, msg);
                    stalog.Info(msg);
                }
            }
        }


        public void ReadStationInfoByclient(WebSocketSession session, string station)
        {
            string[] strArray = ReadStationInfoByClent(station);
            var stationInfoString = Newtonsoft.Json.JsonConvert.SerializeObject(strArray);
            WebSocketHelper.SendMsgBySession(session, "ReadStation" + stationInfoString);
        }


        /// <summary>
        /// 输送机界面显示
        /// </summary>
        /// <param name="ci"></param>
        private void NotifityUIConveryStatus(object equipinfos)
        {
            if (ShowStationStatus != null)
            {
                if (equipinfos is List<ConveryEntity>)
                {
                    //异步通知界面显示
                    List<ConveryEntity> lstconvery = (List<ConveryEntity>)equipinfos;
                    ShowStationStatus(lstconvery);

                    var stationInfoString = Newtonsoft.Json.JsonConvert.SerializeObject(lstconvery);
                    WebSocketHelper.SendMsgToRemotePoint("StationInfo" + stationInfoString);
                }
            }
        }
        /// <summary>
        /// 输送机界面显示
        /// </summary>
        /// <param name="ci"></param>
        private void ShowConveryPLCStatus(PLCStatus plc)
        {
            if (ShowStationPLCStatus != null)
            {
                ShowStationPLCStatus(plc._IP, plc._elapsedMilliseconds.ToString(), plc._connectStatus);
                var PLCStatusString = Newtonsoft.Json.JsonConvert.SerializeObject(plc);
                WebSocketHelper.SendMsgToRemotePoint("PLCStatus" + PLCStatusString);
            }
        }




        public void send(string ip, ushort port, ushort id, string path, string ledtext)
        {
            LED_MC3000 led3000 = new LED_MC3000(ip, 28123, 1001);
            if (!LEDSendStr.ContainsKey(ip))
            {
                LEDSendStr.Add(ip, "设备运行中 请注意安全");
            }
            if (LEDSendStr[ip] != ledtext)
            {
                led3000.sendText(ledtext);
                LEDSendStr[ip] = ledtext;
            }
        }

        //private bool ConnectLED(string ip, ushort port, string filepath, ushort DevID)
        //{
        //    if (led != null)
        //        led.close();
        //    led = new LED_UDP(ip, port, DevID, filepath);
        //    if (led.open())
        //        return true;
        //    else
        //        return false;
        //}
        public class ArriveInfo
        {
            public string barcode;
            public DateTime dateTime;
            public bool flag;
        }
    }
}
